package com.rupertjones.globalcron.domain;

import org.apache.log4j.Logger;
import org.joda.time.DateTimeZone;

import static java.lang.String.format;

/**
 * <p>&copy Rupert Jones 2012</p>
 *
 * @author rup
 */
public class HostConfigurationJob {
    private static final Logger LOG = Logger.getLogger(HostConfigurationJob.class);

    private HostDAO hostDAO;

    public HostConfigurationJob(HostDAO hostDAO) {
        this.hostDAO = hostDAO;
    }

    public void execute() {
        checkCurrentHost();
        checkTimeZone();
    }

    private void checkCurrentHost() {
        String currentHostName = Host.getCurrentHost();
        DateTimeZone zone = DateTimeZone.getDefault();
        Host host = hostDAO.findByHostName(currentHostName);
        if (host == null) {
            host = new Host();
            host.setTimezoneId(zone.getID());
            host.setEnabled(true);
            host.setHostname(currentHostName);
            host.setName(currentHostName);
            hostDAO.upsert(host);
            LOG.warn(format("Created host for this server [%s]", currentHostName));
        }
    }

    private void checkTimeZone() {
        String currentHostName = Host.getCurrentHost();
        DateTimeZone zone = DateTimeZone.getDefault();
        Host host = hostDAO.findByHostName(currentHostName);
        if (host != null && !zone.equals(host.getTimeZone())) {
            LOG.warn(format("Timezone assigned to this host is incorrect, adjusting from [%s] to [%s]", host.getTimezoneId(), zone.getID()));
            host.setTimezoneId(zone.getID());
            hostDAO.upsert(host);
        }
    }
}
